﻿using System;
using System.Security.Permissions;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Serilog;

namespace TeBigScreenWpf
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        public App()
        {
            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Verbose()
                .WriteTo.Async(a => a.File("logs/tbsw-.log", rollingInterval: RollingInterval.Day))
                .CreateLogger();

            SetUnhandledExceptionHandler(AppDomain.CurrentDomain);

            TendEase.AssemblyResolver.SetResolver();
        }

        [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlAppDomain)]
        internal static void SetUnhandledExceptionHandler(AppDomain domain)
        {
            domain.FirstChanceException += Domain_FirstChanceException;
            domain.UnhandledException += CurrentDomain_UnhandledException;
            Application.Current.DispatcherUnhandledException +=
                Current_DispatcherUnhandledException;
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
        }

        private static void Domain_FirstChanceException(
            object sender,
            System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs e
        )
        {
            //Log.Error(e.Exception.Message);
        }

        private static void CurrentDomain_UnhandledException(
            object sender,
            UnhandledExceptionEventArgs e
        )
        {
            LogException(e.ExceptionObject);
        }

        private static void TaskScheduler_UnobservedTaskException(
            object sender,
            UnobservedTaskExceptionEventArgs e
        )
        {
            LogException(e.Exception);
            e.SetObserved();
        }

        private static void Current_DispatcherUnhandledException(
            object sender,
            System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e
        )
        {
            LogException(e.Exception);
            e.Handled = true;
        }

        private static void LogException(object exObject)
        {
            if (exObject is Exception ex)
            {
                var sb = new StringBuilder();

                sb.AppendLine(ex.Message);
                sb.AppendLine(ex.StackTrace);

                Log.Error(sb.ToString());
            }
        }
    }
}
